import { defineStore } from 'pinia'

const useHttpRequest = defineStore('httpRequest', {
  state: () => ({
    httpRequestList: {} as any,
  }),
  getters: {
    // 获取用户机构
    getHttpRequestList(state) {
      return state.httpRequestList || []
    },
  },
  actions: {
    removeHttpRequestList() {
      this.updateRequestState(0)
    },
    addHttpRequestList(payload: any) {
      this.updateRequestState(payload)
    },
    delHttpRequestList(url: string) {
      Object.keys(this.httpRequestList).forEach((item) => {
        const index = this.httpRequestList[item].indexOf((sitem: any) => sitem.url === url)
        if (index > -1) {
          this.httpRequestList[item].splice(index, 1)
        }
      })
    },
    updateRequestState(payload: any) {
      if (payload === 0) {
        // 强行中断时才向下执行
        Object.keys(this.httpRequestList).forEach((item) => {
          this.httpRequestList[item].forEach((sitem: any) => {
            sitem.cancel('interrupt')
          })
          this.httpRequestList[item] = []
        })
      } else if (this.httpRequestList[payload.key]) {
        this.httpRequestList[payload.key].push({
          url: payload.url,
          cancel: payload.value,
        })
      } else {
        this.httpRequestList[payload.key] = [
          {
            url: payload.url,
            cancel: payload.value,
          },
        ]
      }
    },
  },
})

export default useHttpRequest
